from datetime import datetime, timedelta

from django.db import transaction

from gis.common.exceptions import BizException
from itpay.core.agency import transation_service
from itpay.core.agency.const import AgencyTransactionType
from itpay.core.recharge_order.errors import ERROR_ORDER_STATUS_CONFLICT
from itpay.core.recharge_order.order_service import _get_order
from itpay.utils import maestro_tracker
from itpay.core.recharge_order import order_service
from .models import Order, Comment
from .const import *


def migrate_user_recharge(cursor=None):
    """
    同步用户充值事件
    :return:
    """

    g = 0
    while True:
        orders = Order.objects.filter().order_by('id')
        if cursor:
            orders = orders.filter(id__gt=cursor)
        i = 0
        for o in orders[:500]:
            i += 1
            g += 1
            cursor = o.id
            try:
                maestro_tracker.track_maestro_user_recharge_create(o.id, int(datetime.strftime(o.created_at, '%s')),
                                                                   o.agency_id, o.amount, o.mch_id, o.user_id)

                if o.status == OrderStatus.CHASED.value:
                    success_time = o.success_at or o.updated_at

                    maestro_tracker.track_maestro_user_recharge_success(o.id,
                                                                        int(datetime.strftime(success_time, '%s')),
                                                                        o.agency_id, o.amount, o.mch_id, o.user_id)

                    chased_time = o.chased_at or o.updated_at
                    maestro_tracker.track_maestro_user_recharge_chase(o.id,
                                                                      int(datetime.strftime(chased_time, '%s')),
                                                                      o.agency_id, o.chased_amount, o.mch_id, o.user_id)

                elif o.status in [OrderStatus.SUCCESS.value, OrderStatus.CHASE_FROZEN.value]:
                    success_time = o.success_at or o.updated_at
                    maestro_tracker.track_maestro_user_recharge_success(o.id,
                                                                        int(datetime.strftime(success_time, '%s')),
                                                                        o.agency_id, o.amount, o.mch_id, o.user_id)
            except:
                print('migrate_user_recharge: {}'.format(o.id))
            if i % 100 == 0:
                print('migrate_user_recharge: ' + str(g))

        if i == 0:
            break


def migrate_recharge_comment(cursor=None):
    """
    同步代理投诉
    :return:
    """

    g = 0
    while True:
        comments = Comment.objects.filter().order_by('id')
        if cursor:
            comments = comments.filter(id__gt=cursor)
        i = 0
        for e in comments[:500]:
            i += 1
            g += 1
            cursor = e.id
            try:
                ts = int(datetime.strftime(e.success_at, '%s')) if e.success_at else int(
                    datetime.strftime(e.created_at, '%s'))
                maestro_tracker.track_maestro_user_recharge_comment(e.id, ts,
                                                                    e.agency_id, e.mch_id, e.user_id,
                                                                    e.comment_star, e.comment_rank, e.auto_comment)
            except:
                print('migrate_recharge_comment: {}'.format(e.id))
            if i % 100 == 0:
                print('migrate_recharge_comment: ' + str(g))

        if i == 0:
            break


def fix_notify_mch_add_coin_fail(order_ids):
    """
    修复通知商户上分，商户返回失败，实际已经成功的订单
    :param order_ids:
    :return:
    """
    if not order_ids:
        return

    if not isinstance(order_ids, list):
        order_ids = [order_ids]

    for order_id in order_ids:
        order = order_service._get_order(order_id)

        if order.status != OrderStatus.FAIL.value:
            print("order status not fail {}".format(order.id))

        # 改订单状态
        order.status = OrderStatus.CHASE_FROZEN.value
        order.remark = "通知失败，手动修改订单状态"

        # 扣代理钱

        transation_service.add_bill(order.agency_id, AgencyTransactionType.AGENCY_OUT_RECHARGE_NOTIFY_FAIL_CHASE,
                                    order.id,
                                    -order.amount)

        # 数据埋点
        maestro_tracker.track_maestro_user_recharge_success(order.id,
                                                            int(datetime.strftime(order.updated_at, '%s')),
                                                            order.agency_id, order.amount, order.mch_id, order.user_id)
        order.save()


def fix_order_chase_time_out(order_id, chased_amount):
    """
    修改追分请求已发送到商户，但订单状态刚好变成不可追分的订单数据
    :param order_id:
    :param chased_amount:
    :return:
    """
    if chased_amount <= 0:
        return

    with transaction.atomic():
        m_order = _get_order(order_id, with_lock=True)
        if m_order.status != OrderStatus.CHASE_FROZEN.value:
            raise BizException(ERROR_ORDER_STATUS_CONFLICT)

        m_order.status = OrderStatus.CHASED.value
        m_order.chased_amount = chased_amount
        m_order.remark = "手动修复数据"
        m_order.save()

        transation_service.add_bill(m_order.agency_id, AgencyTransactionType.AGENCY_IN_CHASE, m_order.id,
                                    chased_amount)

    try:
        # 注意这个追分时间
        maestro_tracker.track_maestro_user_recharge_chase(m_order.id, int(
            datetime.strftime(m_order.success_at + timedelta(minutes=20), '%s')),
                                                          m_order.agency_id,
                                                          m_order.chased_amount,
                                                          m_order.mch_id, m_order.user_id)
    except:
        print("track error")
